//
//  LCProductDLMgr.m
//  stone-story
//
//  Created by dodo liu on 12-9-27.
//  Copyright (c) 2012年 liu dodo. All rights reserved.
//

#import "LCProductDLMgr.h"

@interface LCProductDLMgr ()

@end

@implementation LCProductDLMgr
@synthesize mgr_delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self tableView_init];
    [self.view setBackgroundColor:[UIColor whiteColor]];

}
-(void)startDownLoad:(NSMutableDictionary*)nd productImage:(UIImage*)productimage
{
    if(dataArray==nil)
         dataArray=[[NSMutableArray alloc]init];
    if(imageArray==nil)
         imageArray=[[NSMutableArray alloc]init];
    if(progressArray==nil)
         progressArray=[[NSMutableArray alloc]init];
    if(productInfoArray==nil)
         productInfoArray=[[NSMutableArray alloc]init];

    [dataArray insertObject:nd atIndex:0];
    [imageArray insertObject:productimage atIndex:0];
    
    UIProgressView *progressIndicator = [[UIProgressView alloc]init]; 
    [progressArray insertObject:progressIndicator atIndex:0]; 
    
     NSLog(@"dataArray count:%d",dataArray.count);
     NSLog(@"imageArray count:%d",imageArray.count);
    
    NSArray *urlArray=[[nd valueForKey:@"product_photos"] componentsSeparatedByString:@","];
    if(filemanager==nil)
    filemanager=[[LCFileManager alloc]init];
    filemanager.delegate=self;
    [filemanager downLoadFilesWithUrlArray:urlArray UIProgressView:progressIndicator queueIdentifier:[nd valueForKey:@"product_id"] saveToPath:@"Documents/products/" folderName:[nd valueForKey:@"product_id"]];
    
     [tableview reloadData];
    [productInfoArray insertObject: nd atIndex:0];
    
}
//下载的委托方法
-(void)queueFilish:(NSString *)queueIdentifier
{
    NSLog(@"the queue indetifier is:%@",queueIdentifier);
    
   
    for(int i=0;i<productInfoArray.count;i++)
    {
        NSMutableDictionary *dictionary=[productInfoArray objectAtIndex:i];
        if([[dictionary valueForKey:@"product_id"] isEqualToString:queueIdentifier])//找出要下载完的产品信息，准备写入数据库
        {
            [self FMDB_init];
            [self createTable];
            [self insertRecordWithDictionary:dictionary];
            [self queryTable];
            
            [LCFileManager saveImageAsJpgFile:[imageArray objectAtIndex:i]
                                          path:@"Documents/products/logo" 
                                      fileName:[LCFileManager getFileNameFormUrl:[dictionary valueForKey:@"product_logo"]]
                                                ];
            
            [mgr_delegate finishDownLoad:queueIdentifier];
            //UILabel *stateLabel=(UILabel*)[self.view viewWithTag:800+i];
            //[stateLabel setText:@"下载完成."];
            //[finishDLArray insertObject:[NSNumber numberWithInt:i] atIndex:0];
        }
        
    }
    
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - 数据表视图



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Return the number of rows in the section.
    return dataArray.count;// [self.resultArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    else {
        //重用CELL时候清空 SUBviews
        for(UIView *view in [cell.contentView subviews])
        {
            [view removeFromSuperview];
        }
    }
    
    // Configure the cell...
    //NSDictionary *cell_text = [self.titleArray objectAtIndex:indexPath.row];
    
    int row=[indexPath row];
    
    
    
    NSMutableDictionary *nd=[dataArray objectAtIndex:row];
    
    //行背景图片
    UIImageView *cellBackImageView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
    cellBackImageView.backgroundColor=[UIColor clearColor];
    cellBackImageView.image =[UIImage imageNamed:@"bg_news_item.png"];
    [cellBackImageView setAlpha:0.5];    
    [cell.contentView addSubview:cellBackImageView];
    
    //左边图片
    UIImageView *cellImageView=[[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
    cellImageView.backgroundColor=[UIColor clearColor];
    [cellImageView setImage:[imageArray objectAtIndex:row]];
    //[ZSImageViewCom setViewRadius:newsImageView theCornerRadius:8 theBorderWidth:0];
    [cell.contentView addSubview:cellImageView];
    
    //产品名称
    UILabel *productName=[[UILabel alloc]initWithFrame:CGRectMake(cellImageView.frame.origin.x
                                                                +cellImageView.frame.size.width+8,17,190, 20)] ;
    [productName setFont:[UIFont fontWithName:@"Thonburi-Bold" size:14.0]];
    [productName setTextColor:[UIColor blackColor]];
    [productName setNumberOfLines:1]; 
    [productName setBackgroundColor:[UIColor clearColor]]; 
    [productName setText:[nd  objectForKey:@"product_name"]];
    [productName setNumberOfLines:2]; 
    [cell.contentView addSubview:productName];
    
    /*
    //下载状态
    UILabel *downState=[[UILabel alloc]initWithFrame:CGRectMake(productName.frame.origin.x,productName.frame.origin.y+productName.frame.size.height,190, 20)] ;
    [downState setFont:[UIFont fontWithName:@"Thonburi-Bold" size:14.0]];
    [downState setTextColor:[UIColor grayColor]];
    [downState setNumberOfLines:1]; 
    [downState setBackgroundColor:[UIColor clearColor]]; 
   // if(![finishDLArray containsObject:[NSNumber numberWithInt:row]])
   
       // [downState setText:@"正在下载..."];

    [downState setNumberOfLines:2];
    [downState setTag:800+row];
    [cell.contentView addSubview:downState];
    */
    //进度条
 
    UIProgressView *progressIndicator=[progressArray objectAtIndex:row]; 
       [progressIndicator setFrame:CGRectMake(70,40, 222, 10)];
        [cell.contentView addSubview:progressIndicator];

    
    cell.selectionStyle=UITableViewCellStyleDefault;
    
    
    return cell;
    
}



-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 70;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //  NSMutableDictionary *nd=[dataArray objectAtIndex:indexPath.row];
    NSLog(@"点击了第[%d]条新闻",indexPath.row);
 
}


//将label文本垂直置顶
-(void)setAligTop:(UILabel *)label
{   label.numberOfLines=3;
    CGSize maxSize=CGSizeMake(label.frame.size.width, 50);
    label.adjustsFontSizeToFitWidth = NO;
    
    // get actual height
    CGSize actualSize=[label.text sizeWithFont:label.font constrainedToSize:maxSize lineBreakMode:label.lineBreakMode];
    CGRect rect=label.frame;
    rect.size.height=actualSize.height;
    
    label.frame=rect;
    
}
- (void)tableView_init 
{
    if(tableview==nil){
    CGRect tableFrame=CGRectMake(0, 0, 300 , 620); //矩形结构
    tableview=[[UITableView alloc]initWithFrame:tableFrame]; //分配内存，设置样式
    [tableview setDelegate:self]; //设置代理
    [tableview setDataSource:self]; //设置数据源
    [tableview setBackgroundColor:[UIColor clearColor]];
    [tableview setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    [self.view addSubview:tableview]; //添加到父视图
    }
}

#pragma mark - 数据库操作
//创建或打开数据库
- (void)FMDB_init//1
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    //dbPath： 数据库路径，在Document中。
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"db_stoneStory.db"];
    //创建数据库实例 db  这里说明下:如果路径中不存在"Test.db"的文件,sqlite会自动创建"Test.db"
    db= [FMDatabase databaseWithPath:dbPath];
    if (![db open]) {
        NSLog(@"Could not open db.");
        return ;
    }
    else {
        NSLog(@"open db. success!");
    }
}

//创建表
- (void)createTable
{
    //创建一个名为User的表，四个字段 书的ID,书的图片文件名,书的pdf文件名,书的排号
    if(!isExistTable(db, @"Products"))
        [db executeUpdate:@"CREATE TABLE Products (product_type integer,product_id integer , product_name text ,product_logo text,product_price text ,product_purchase text , product_wholesale text )"];
    else {
        NSLog(@"table db.Products have exist!");
    }
}

//插入数据
- (void)insertRecordWithDictionary:(NSMutableDictionary*)nd
{ 
    
    if(isExistTable(db, @"Products"))
    {
        NSNumber *product_type=[NSNumber numberWithInt:[[nd valueForKey:@"product_type"]intValue]];
        NSNumber *product_id=[NSNumber numberWithInt:[[nd valueForKey:@"product_id"]intValue]];
        NSString *product_name=[nd valueForKey:@"product_name"];
        NSString *product_logo=[LCFileManager getFileNameFormUrl:[nd valueForKey:@"product_logo"]];
        NSString *product_price=[nd valueForKey:@"product_price"];
        NSString *product_purchase=[nd valueForKey:@"product_purchase"];
        NSString *product_wholesale=[nd valueForKey:@"product_wholesale"];
        
        [db executeUpdate:@"INSERT INTO Products (product_type,product_id,product_name,product_logo,product_price,product_purchase,product_wholesale) VALUES (?,?,?,?,?,?,?)",product_type,product_id,product_name,product_logo,product_price,product_purchase,product_wholesale] ;
        
    }
    else {
        NSLog(@"table db.Products have exist!");
    }
}

//查询
- (void)queryTable
{
    //返回数据库中第一条满足条件的结果
    //   NSString *aa=[db stringForQuery:@"SELECT Name FROM User WHERE Age = ?",@"20"];
    
    //返回全部查询结果
    FMResultSet *rs=[db executeQuery:@"SELECT * FROM Products ORDER BY product_id ASC"];
    
    //rs=[db executeQuery:@"SELECT * FROM User WHERE Age = ?",@"20"];
    
    while ([rs next]){
        NSLog(@"\n product_type:%@ \n product_id:%@\n \n product_name:%@ \n product_logo:%@ \n product_price:%@ \n product_purchase:%@ \n product_wholesale:%@",[rs stringForColumn:@"product_type"],[rs stringForColumn:@"product_id"],[rs stringForColumn:@"product_name"],[rs stringForColumn:@"product_logo"],[rs stringForColumn:@"product_price"],[rs stringForColumn:@"product_purchase"],[rs stringForColumn:@"product_wholesale"]);
    }
    
    [rs close];
}


//更新数据 将“张三”更改为“李四”
-(void)updateRecord
{
    
    [db executeUpdate:@"UPDATE User SET Name = ? WHERE Name = ? ",@"李四",@"张三"];
    
}


//删除数据
- (void)deleteRecord
{
    [db executeUpdate:@"DELETE FROM Products WHERE product_id = ?",[NSNumber numberWithInt:3]];
}

//是否存在表
BOOL isExistTable(FMDatabase *db,NSString * tableName)
{
    FMResultSet *rs = [db executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", tableName];
    while ([rs next])
    {
        // just print out what we've got in a number of formats.
        NSInteger count = [rs intForColumn:@"count"];
        NSLog(@"isTableOK %d", count);
        
        if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    
    return NO;
}







@end
